package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-man/cache"
	"order-man/model"
	"strconv"
	"time"
)

func GoodAdd(c *gin.Context) {
	good_code := c.PostForm("good_code")
	good_name := c.PostForm("good_name")
	data := model.Good{
		GoodCode: good_code,
		GoodName: good_name,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func GoodOrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	good_id, _ := strconv.Atoi(c.PostForm("good_id"))
	data := model.Order{
		OrderCode:  order_code,
		OrderPrice: order_price,
		GoodId:     good_id,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func GoodOrderList(c *gin.Context) {
	/*
			SELECT
		  goods.good_code AS GoodCode,
		  goods.good_name AS GoodName,
		  orders.order_code AS OrderCode,
		  orders.order_price AS OrderPrice
		FROM
		  orders
		  LEFT JOIN goods ON orders.good_id = goods.id
	*/
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	redis_key := "list_page" + strconv.Itoa(page)
	var order []model.GoodOrder
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"orders.order_code AS OrderCode",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN goods ON orders.good_id = goods.id").
			Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  order,
		"total": total,
	})
}
func GoodOrderFind(c *gin.Context) {
	id := c.Query("id")
	redis_key := "order_find_" + id
	var order model.GoodOrder
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select(
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"orders.order_code AS OrderCode",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN goods ON orders.good_id = goods.id").
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": order,
	})
}
